package com.snatch.snatchmgr.service.impl;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.snatch.common.utils.CommonUtil;
import com.snatch.common.vo.ErrorLog;
import com.snatch.common.vo.HeartbeatInput;
import com.snatch.common.vo.HeartbeatOutput;
import com.snatch.common.vo.NodeManageInput;
import com.snatch.common.vo.NodeManageOutput;
import com.snatch.common.vo.NodeRegisterOutput;
import com.snatch.common.vo.NodeTaskInput;
import com.snatch.common.vo.NodeWeb;
import com.snatch.common.vo.SnatchState;
import com.snatch.snatchmgr.core.SnatchCtrlManage;
import com.snatch.snatchmgr.core.SnatchItemCore;
import com.snatch.snatchmgr.nodemanage.NodeManageIntegration;
import com.snatch.snatchmgr.service.MatchDataService;
import com.snatch.snatchmgr.service.ReceieveInnerDataService;
import com.snatch.snatchmgr.system.SystemData;
import com.snatch.snatchmgr.vo.SnatchGame;
import com.snatch.snatchmgr.vo.SnatchItem;
import com.snatch.snatchmgr.vo.SnatchWeb;
import com.snatch.snatchmgr.vo.WebSnatchInfo;
import com.thoughtworks.xstream.XStreamException;

/**
 * 处理节点通过ICE发送的数据包
 */
@Service
public class ReceieveInnerDataServiceImpl implements ReceieveInnerDataService {

	@Autowired
	private NodeManageIntegration nodeManageIntegration;
	
	@Autowired
	private SnatchCtrlManage snatchCtrlManage;
	
	@Autowired
	private MatchDataService matchDataService;
	
	
	/**
	 * 做负载 没用
	 */
	static public ConcurrentMap<String, Integer> snatchItemStatus = new ConcurrentHashMap<String, Integer>();// 每个抓取线程的名字和线程ID
	// 日志对象
	private Logger log = Logger.getLogger(ReceieveInnerDataServiceImpl.class);

	@Override
	public String doError(String xmlStr) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String doThirdHeartbeat(String xmlStr) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String doHeartbeat(String xmlStr) {
		HeartbeatOutput heartbeatOutput = new HeartbeatOutput();
		try {
			HeartbeatInput heartbeatInput = JSON.parseObject(xmlStr,HeartbeatInput.class);
			for(SnatchState snatchState : heartbeatInput.getSnatchStates()){
				if(snatchState.isOpen()){
					SystemData.validNode(2, heartbeatInput.getOnlyCode(),snatchState.getWebCode(),snatchState.getSystemCode(),snatchState.getLoginAccunts());
				}else{
					SystemData.validNode(1, heartbeatInput.getOnlyCode(),snatchState.getWebCode(),snatchState.getSystemCode(),null);
				}
				upNodeTime(snatchState.getWebCode(), heartbeatInput.getOnlyCode(), snatchState.getSnatchItems());
			}
			heartbeatOutput.setStatus(1);
		} catch (XStreamException e) {
			e.printStackTrace();
			heartbeatOutput.setStatus(0);
			heartbeatOutput.setRemark("数据格式不对!");
		} catch (Exception e) {
			e.printStackTrace();
			heartbeatOutput.setStatus(0);
			heartbeatOutput.setRemark("其他异常!" + e);
		}
		String xmlstr = JSON.toJSONString(heartbeatOutput);
		return xmlstr;
	}
	
	public void upNodeTime(String webCode,String nodeOnlyCode,List<String> snatchItems){
		SnatchWeb snatchWeb = SystemData.findSnatchWeb(webCode);
		if(null != snatchWeb){
			for(SnatchGame snatchGame : snatchWeb.getSnatchGames()){
				for(SnatchItem snatchItem : snatchGame.getSnatchItems()){
					if(snatchItems.contains(snatchItem.itemOnlyCode())){
						snatchItem.updateNodeTime(nodeOnlyCode);
					}
				}
			}
		}
	}

	@Override
	public String nodeRegister(String xmlStr) {
		String code = "";
		NodeRegisterOutput nodeRegisterOutput = new NodeRegisterOutput();
		try {
			NodeWeb nodeWeb =  JSON.parseObject(xmlStr, NodeWeb.class); 
			code = nodeWeb.getOnlyCode();
			nodeManageIntegration.addIceClient(nodeWeb.getIp(), nodeWeb.getOnlyCode());// 把ICE客户端加入MAP队列中
			SystemData.removeWebSnatchInfo(code);
			SystemData.addWebSnatchInfo(nodeWeb);

			/*for (Config config : nodeRegisterInput.getConfigs()) {// 把节点的每个抓取项信息放入内存数据中
				SnatchItemInfo snatchItemInfo = new SnatchItemInfo();
				snatchItemInfo.setOnlyCode(nodeRegisterInput.getOnlyCode());
				snatchItemInfo.setOperatorStatus(0);
				snatchItemInfo.setSnatchItemName(config.getSnatchItem());
				snatchItemInfo.setHasException(1);
				snatchItemInfo.setThirdSystem(config.getThirdSystem());
				nodeInfo.getSnatchItemList().add(snatchItemInfo);
			}*/
			nodeRegisterOutput.setStatus(1);

		} catch (XStreamException e) {
			e.printStackTrace();
			nodeRegisterOutput.setStatus(0);
			nodeRegisterOutput.setRemark("数据格式不对!");
		} catch (Exception e) {
			//SystemData.hasError = true;

			ErrorLog errorLog = new ErrorLog();
			errorLog.setErrorDesc("注册节点发生其他异常：" + e);
			errorLog.setErrorNode("管理中心");
			//errorDao.addError(errorLog);

			e.printStackTrace();
			nodeRegisterOutput.setStatus(0);
			nodeRegisterOutput.setRemark("其他异常!" + e.getMessage());
		}
		String xmlstr= JSON.toJSONString(nodeRegisterOutput);
		return xmlstr;
	}

	@Override
	public void doParseXML(String xmlStr) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public String versionCode(String xmlStr) {
		if(null == xmlStr || "".equals(xmlStr)) return "-1";
		return SystemData.findVersionAdd(xmlStr)+"";
	}

	@Override
	public String nodeRun(String nodeCode,String webCode) {
		List<WebSnatchInfo> list = SystemData.getWebSnatchInfos(webCode);
		if(list!= null){
			for(WebSnatchInfo webSnatchInfo : list){
				if(webSnatchInfo.getOnlyCode().equals(nodeCode) && webSnatchInfo.getValid() ==1){
					NodeManageInput nodeManageInput = new NodeManageInput();
					nodeManageInput.setOnlyCode(webSnatchInfo.getOnlyCode());
					nodeManageInput.setWebCode(webSnatchInfo.getWebCode());
					nodeManageInput.setOperate(1);
					NodeManageOutput nodeManageOutput =nodeManageIntegration.nodeManage(nodeManageInput);
					if(nodeManageOutput.getStatus() == 1){
						webSnatchInfo.setValid(2);
						return "1";
					}
				}
				
			}
		}
		return "-1";
	}

	
	@Override
	public String snatchTask(NodeTaskInput nodeTaskInput){
		//策略所有节点都发任务  
		 List<WebSnatchInfo> webSnatchInfos = SystemData.getWebSnatchInfos(nodeTaskInput.getWebCode());
		 if(null == webSnatchInfos) return "-1";
		 for(WebSnatchInfo webSnatchInfo : webSnatchInfos){
			 nodeTaskInput.setOnlyCode(webSnatchInfo.getOnlyCode());
			 nodeManageIntegration.snatchTask(nodeTaskInput);
		 }
		 return "1";
	}

	@Override
	public String ratioDataInput(String xmlStr) {
		try {
			final String[] strArr = CommonUtil.parsePerfix(xmlStr, 3, ";");
			final long seqCode = Long.parseLong(strArr[1]);
			if(SystemData.compareToVersion(strArr[0], seqCode)){
				SnatchItemCore snatchItemCore = snatchCtrlManage.findSnatchItemCore(strArr[0]);
				if(null == snatchItemCore){
					log.info("找不到任务线程 可能任务已取消"+strArr[0]);
					return "-1";
				}
				snatchItemCore.notifyAllQueue(strArr[2]);
			}
		} catch (Exception e) {
			log.error("赔率接口出错！",e);
			//SystemData.hasError = true;
//
//			ErrorLog errorLog = new ErrorLog();
//			errorLog.setErrorDesc("注册节点发生其他异常：" + e);
//			errorLog.setErrorNode("管理中心");
//			//errorDao.addError(errorLog);
//
//			e.printStackTrace();
//			nodeRegisterOutput.setStatus(0);
//			nodeRegisterOutput.setRemark("其他异常!" + e.getMessage());
			return "-2";
		}
		return "1";
	}

	@Override
	public List<WebSnatchInfo> findWebSnatchInfos(String webCode) {
		return  SystemData.getWebSnatchInfos(webCode);
	}

	
	
	
	
	
	
}
